from .. import *
from ..models import ent_order, psn
from ..models import psn_resume
from ..models import ent
from ..models import ent_jobs
from ..models import ent_baseInfo
from ..models import psn_resume_project_exprience
from ..models import psn_resume_work_exprience
from ..models import psn_resume_edu_exprience
from ..models import send_job
from ..util.wxpay_util import WxPayUtil
from ..util.wxpay_v2_util import WxPayUtilV2
from ..util.redis_util import GetWxPayFromRedis


# 设置首页index.html
@csrf_exempt
def returnIndex(request):
    return render(request, 'index.html')


# 查询账号信息
@csrf_exempt
def getAccountInfo(request):
    message = json.loads(request.body)
    accid = message['id']
    type = message['type']
    if type == 'psn':
        msg = serializers.serialize('json', psn.objects.filter(psnId=accid))
        return Response(msg=msg)
    if type == 'ent':
        msg = serializers.serialize('json', ent.objects.filter(entId=accid))
        return Response(msg=msg)


# 修改账号信息
@csrf_exempt
def setAccountInfo(request):
    message = json.loads(request.body)
    accid = message['id']
    m = message['msg']
    if psn.objects.get(username=m['username']).psnId != accid:
        return ErrResponse("用户名已存在，请更换")
    if psn.objects.get(email=m['email']).psnId != accid:
        return ErrResponse("邮箱已被注册，请更换")
    if psn.objects.get(tel=m['tel']).psnId != accid:
        return ErrResponse("手机已被注册，请更换")
    updateAcc = psn.objects.filter(
        psnId=accid).update(username=m['username'], tel=m['tel'], email=m['email'], password=m['password'])
    if not updateAcc:
        return ErrResponse("保存失败")
    return Response("保存成功")


# 简历投递
@csrf_exempt
def sendResume(request):
    message = json.loads(request.body)
    psnId = message['psnId']
    jobId = message['jobId']
    psnEmail = psn.objects.get(psnId=psnId).email
    psnTel = psn.objects.get(psnId=psnId).tel
    resumeId = psn_resume.objects.filter(psnId=psnId)[0].resumeId
    entId = ent_jobs.objects.get(jobId=jobId).entId
    entEmail = ent.objects.get(entId=entId).email
    entTel = ent.objects.get(entId=entId).tel
    jobName = ent_jobs.objects.get(jobId=jobId).jobName
    entName = ent_jobs.objects.get(jobId=jobId).entName
    name = psn_resume.objects.get(resumeId=resumeId).name
    wantJobPay = psn_resume.objects.get(resumeId=resumeId).jobPay
    wantJobName = psn_resume.objects.get(resumeId=resumeId).jobName
    wantJobAdd = psn_resume.objects.get(resumeId=resumeId).jobAdd
    if send_job.objects.filter(resumeId=resumeId, jobId=jobId):
        return ErrResponse("请勿重复投递")
    addNewRec = send_job(recordId=getId(), resumeId=resumeId,
                         jobId=jobId, entId=entId, psnId=psnId, jobName=jobName, entName=entName, name=name, wantJobName=wantJobName, wantJobPay=wantJobPay, wantJobAdd=wantJobAdd, psnEmail=psnEmail, psnTel=psnTel, entEmail=entEmail, entTel=entTel, sendTime=datetime.date.today())
    if addNewRec.save():
        return ErrResponse("投递失败")
    return Response("投递成功")


# 查询已投递的职位
@csrf_exempt
def getSentJob(request):
    message = json.loads(request.body)
    if message['psnId']:
        psnId = message['psnId']
        resumeId = psn_resume.objects.filter(psnId=psnId)[0].resumeId
        msg = serializers.serialize(
            'json', send_job.objects.order_by(
                "sendTime").filter(resumeId=resumeId))
        return Response(msg=msg)
    if message['entId']:
        entId = message['entId']
        msg = serializers.serialize(
            'json', send_job.objects.filter(entId=entId))
        return Response(msg=msg)
    return ErrResponse('')


# 通过投递
@csrf_exempt
def passSent(request):
    '''
    0 - 订单已关闭
    1 - 个人已同意
    2 - 面试邀请
    3 - 个人拒绝
    4 - 企业拒绝
    5 - 已送达
    '''
    message = json.loads(request.body)
    m = message['msg']
    jobId = m['jobId']
    entId = m['entId']
    psnId = m['psnId']
    resumeId = m['resumeId']

    if isErrorId(jobId):
        return ErrResponse("")

    if isErrorId(entId):
        return ErrResponse("")

    if isErrorId(entId):
        return ErrResponse("")

    if isErrorId(entId):
        return ErrResponse("")

    psnInfoInner = psn.objects.filter(psnId=psnId).first()
    if not psnInfoInner:
        return ErrResponse("")
    entInfoInner = ent.objects.filter(entId=entId).first()
    if not entInfoInner:
        return ErrResponse("")

    jobInfoInner = ent_jobs.objects.filter(jobId=jobId).first()
    if not jobInfoInner:
        return ErrResponse("")
    resumeInfoInner = psn_resume.objects.filter(resumeId=resumeId).first()
    if not resumeInfoInner:
        return ErrResponse("")

    jobName = jobInfoInner.jobName
    entName = jobInfoInner.entName
    name = resumeInfoInner.name
    wantJobPay = resumeInfoInner.jobPay
    wantJobName = resumeInfoInner.jobName
    wantJobAdd = resumeInfoInner.jobAdd
    entEmail = entInfoInner.email
    entTel = entInfoInner.tel
    psnEmail = psnInfoInner.email
    psnTel = psnInfoInner.tel

    send_job_info = send_job.objects.filter(
        entId=entId, psnId=psnId, resumeId=resumeId, jobId=jobId).first()
    if not send_job_info:
        send_job_info = send_job(
            recordId=getId(), entId=entId, psnId=psnId, resumeId=resumeId, jobId=jobId)

    send_job_info.jobName = jobName
    send_job_info.entName = entName
    send_job_info.name = name
    send_job_info.wantJobName = wantJobName
    send_job_info.wantJobPay = wantJobPay
    send_job_info.wantJobAdd = wantJobAdd
    send_job_info.psnEmail = psnEmail
    send_job_info.psnTel = psnTel
    send_job_info.entEmail = entEmail
    send_job_info.entTel = entTel
    if request.session.get('psnId'):
        send_job_info.status = '1'
        send_job_info.sendTime = datetime.date.today()
        send_job_info.save()
        return Response("已同意")
    if request.session.get('entId'):
        send_job_info.status = '2'
        send_job_info.sendTime = datetime.date.today()
        send_job_info.save()
        return Response("操作成功")
    return ErrResponse("")


# 拒绝投递
@csrf_exempt
def closeSent(request):
    message = json.loads(request.body)
    m = message['msg']
    jobId = m['jobId']
    resumeId = m['resumeId']
    entId = m['entId']
    psnId = m['psnId']
    send_job_info = send_job.objects.filter(
        entId=entId, psnId=psnId, resumeId=resumeId, jobId=jobId).first()
    if not send_job_info:
        return ErrResponse("")
    if request.session.get('psnId'):
        send_job_info.status = '3'
        send_job_info.status = datetime.date.today()
        send_job_info.save()
        return Response("已拒绝")
    if request.session.get('entId'):
        send_job_info.status = '4'
        send_job_info.status = datetime.date.today()
        send_job_info.save()
        return Response("已拒绝")
    return ErrResponse('')


# 关闭投递
@csrf_exempt
def delSent(request):
    message = json.loads(request.body)
    status = 'error'
    msg = ''
    m = message['msg']
    jobId = m['jobId']
    resumeId = m['resumeId']
    entId = m['entId']
    psnId = m['psnId']
    res = send_job.objects.filter(
        entId=entId, psnId=psnId, resumeId=resumeId, jobId=jobId).update(status='0', sendTime=datetime.date.today())
    status = 'ok'
    msg = '已关闭'
    return Response(msg=msg)


# 个人用户查询职位
@csrf_exempt
def searchJob(request):
    message = json.loads(request.body)

    jobId = message['jobId']  # key为jobid
    searchMsg = message['searchMsg']
    if isErrorId(jobId):
        if not searchMsg:
            res = ent_jobs.objects.all()
            msg = serializers.serialize(
                'json', res)
            return Response(msg)

        # 如果有搜索条件
        m = message['searchMsg']  # m 为搜索条件
        res = ent_jobs.objects.all()
        if m['jobType']:
            res = res.filter(jobType=m['jobType'])
        if m['jobPay']:
            res = res.filter(jobPay=m['jobPay'])
        if m['workExp']:
            res = res.filter(workExp=m['workExp'])
        if m['degree']:
            res = res.filter(degree=m['degree'])
        if m['func']:
            res = res.filter(Q(jobFunc__icontains=m['func']) | Q(
                jobName__icontains=m['func']))
        if 'otherInfo' in m:
            res = res.filter(
                Q(jobName__icontains=m['otherInfo']) | Q(entName__icontains=m['otherInfo']))
        msg = serializers.serialize('json', res)
        return Response(msg)
    msg = {}
    msg['entJobInfo'] = serializers.serialize(
        'json', ent_jobs.objects.filter(
            jobId=jobId))
    entId = ent_jobs.objects.get(
        jobId=jobId).entId
    msg['entBaseInfo'] = serializers.serialize(
        'json', ent_baseInfo.objects.filter(
            entId=entId))
    return Response(msg=json.dumps(msg))


# 个人用户查询去企业
@csrf_exempt
def searchEnt(request):
    message = json.loads(request.body)

    entId = message['entId']
    searchMsg = message['searchMsg']
    if isErrorId(entId):
        if not searchMsg:
            res = ent_baseInfo.objects.all()
            msg = serializers.serialize(
                'json', res)
            return Response(msg)

        # 如果有搜索条件
        m = message['searchMsg']  # m 为搜索条件
        res = ent_baseInfo.objects.all()
        if m['scale']:
            res = res.filter(entScale=m['scale'])
        if m['class']:
            res = res.filter(entClass=m['class'])
        if m['keywords']:
            res = res.filter(
                Q(entName__icontains=m['keywords']))
        msg = serializers.serialize('json', res)
        return Response(msg)
    msg = serializers.serialize(
        'json', ent_baseInfo.objects.filter(
            entId=entId))
    return Response(msg=msg)


# 企业用户用户查询个人
@csrf_exempt
def searchPsn(request):
    message = json.loads(request.body)
    msg = {}
    resumeId = message['resumeId']
    searchMsg = message['searchMsg']
    if not resumeId:
        if not searchMsg:
            res = psn_resume.objects.all()
            msg = serializers.serialize(
                'json', res)
            return Response(msg=msg)
        # 如果有搜索条件searchMsg
        res = psn_resume.objects.all()
        if searchMsg['jobType']:
            res = res.filter(jobType=searchMsg['jobType'])
        if searchMsg['jobPay']:
            res = res.filter(jobPay=searchMsg['jobPay'])
        if searchMsg['workExp']:
            res = res.filter(workExp=searchMsg['workExp'])
        if searchMsg['degree']:
            res = res.filter(degree=searchMsg['degree'])
        if searchMsg['jobAdd']:
            res = res.filter(jobAdd=searchMsg['jobAdd'])
        if 'otherInfo' in searchMsg:
            res = res.filter(
                Q(jobAdd__icontains=searchMsg['otherInfo']) | Q(jobName__icontains=searchMsg['otherInfo']))
        msg = serializers.serialize('json', res)
        return Response(msg=msg)

    msg['psnBaseInfo'] = model_to_dict(
        psn_resume.objects.get(resumeId=resumeId))
    msg['psnProjectInfo'] = serializers.serialize(
        'json', psn_resume_project_exprience.objects.order_by(
            "startTime").filter(
            resumeId=resumeId))
    msg['psnWorkInfo'] = serializers.serialize(
        'json', psn_resume_work_exprience.objects.order_by(
            "startTime").filter(
            resumeId=resumeId))
    msg['psnEduInfo'] = serializers.serialize(
        'json', psn_resume_edu_exprience.objects.order_by(
            "gradTime").filter(
            resumeId=resumeId))
    return Response(msg=msg)


# 发送邮件测试
@csrf_exempt
def sendEmail(psnEmail, entname, name, jobname, conname, entTel, entEmail):
    title = u'邮件主题'
    host = 'qiulangcheng@qlcnb.club'
    resHostList = []
    resHostList.append(psnEmail)
    resHost = resHostList
    html_content = name+"<h2>您好！</h2> <p>企业：" + \
        entname + "。</p> <p>向您推荐了职位</p>"+jobname+'。<p>企业联系人：' + \
        conname+'</p><p>联系邮箱：'+entEmail+'</p><p>联系电话：'+entTel+'</p>'
    email = EmailMessage(title, html_content, host, resHost)
    email.content_subtype = "html"
    if email.send():
        return "ok"
    else:
        return "error"


@csrf_exempt
def getXZInfo(request):
    url = "https://m.abing81.cn/Psninfo/Psninfo/GetInf"
    strparam = json.dumps({"keywords": "", "nation": "", "funcname": "", "industry": "",
                           "scale": "", "entclass": "", "salary": "", "edu": "", "jobworktype": "", "datenum": 30})
    for page in range(0, 25):
        params = {
            "pagename": "alljoblist",
            "countnum": 100,
            "currpage": page,
            "strparam": strparam
        }
        res = requests.get(url=url, params=params)

        res = json.loads(res.content)
        job_list = json.loads(res).get('msg').get("ListJobInf")
        for item in job_list:
            jobInfo = item['JobInf']
            jobName = jobInfo['entJobName']
            jobName = str(jobName)
            if jobName.find("军") >= 0:
                continue
            entAddress = jobInfo['entJobAdd']
            if not entAddress:
                continue
            jobPay = jobInfo['entJobPay']
            if not jobPay:
                jobPay = '面议'
                entId = getIdFromUUID(jobInfo['entid'])
                entName = item['EntName']
                entIndustry = item['EntIndustry']
                entTag = jobInfo['entWelfareTag']

                ent(entId=entId, username=entName, password="123456").save()

                ent_baseInfo(entId=entId, entAddress=entAddress, entName=item['EntName'],
                             entClass=item['EntClass'], entScale=item['EntScale'], entIndustry=entIndustry, entTag=entTag).save()
                ent_jobs(jobId=getIdFromUUID(jobInfo['jobId']),
                         jobName=jobName,
                         jobAddress=entAddress,
                         jobType=jobInfo['entJobWorkType'],
                         degree=jobInfo['entJobEdu'],
                         jobPay=jobPay,
                         jobReq=jobInfo['JobPost'],
                         entId=entId,
                         entName=entName, entTag=entTag, jobFunc=jobInfo['entJobFun']).save()

    return Response()


@csrf_exempt
def Pay(request):
    message = json.loads(request.body)
    totalPrice = message["totalPrice"]
    entId = message["entId"]
    if isErrorId(entId):
        return ErrResponse("")
    beforeEntJobCount = ent.objects.get(entId=entId).entJobCount
    orderId = getId()
    wx_util = WxPayUtil()
    code_url = wx_util.wx_native_pay(totalPrice=totalPrice, orderId=orderId)

    changeEntJobCount = 0
    ent_order(orderId=orderId, entId=entId, orderStatus=0, totalPrice=totalPrice,
              beforeEntJobCount=beforeEntJobCount,
              changeEntJobCount=changeEntJobCount,
              afterEntJobCount=beforeEntJobCount).save()
    res = {
        "orderId": orderId,
        "codeImg": code_url
    }
    return Response(res)


@csrf_exempt
def GetPay(request):
    message = json.loads(request.body)
    orderId = message["orderId"]
    if isErrorId(orderId):
        return ErrResponse("")

    redis_util = GetWxPayFromRedis(orderId)
    orderInfo = redis_util.get_order()
    if not orderInfo:
        return WiteResponse()

    try:
        entOrderInner = ent_order.objects.get(orderId=orderId)
    except ent_order.DoesNotExist:
        return ErrResponse("")
    entId = entOrderInner.entId
    try:
        entAccount = ent.objects.get(entId=entId)
    except ent.DoesNotExist:
        return ErrResponse("")

    totoalPrice = entOrderInner.totalPrice
    beforeEntJobCount = entOrderInner.beforeEntJobCount
    changeEntJobCount = totoalPrice/100
    afterEntJobCount = beforeEntJobCount + changeEntJobCount
    trade_state = orderInfo['trade_state']
    if trade_state != "SUCCESS":
        entOrderInner.orderStatus = 2
        entOrderInner.save()
        return ErrResponse("")
    entOrderInner.orderStatus = 1
    entOrderInner.changeEntJobCount = changeEntJobCount
    entOrderInner.afterEntJobCount = afterEntJobCount
    entAccount.entJobCount = afterEntJobCount
    entOrderInner.save()
    entAccount.save()
    return Response()


@csrf_exempt
def reportJob(request):
    return Response()


@csrf_exempt
def wxEntPay(requset):
    orderId = getId()
    wx_util = WxPayUtilV2()
    wx_util.wx_ent_pay(orderId=orderId,openId="o2ucL414QHvBFrhZ4KkdzhyLYDtA",re_user_name="裘浪城")
    return Response()
